import {get, post} from './request'
import api from '../config/api'
export function getSetting(auth, onSuccess, onFail) {
    mpvue.getSetting({
    success(res) {
        console.log(res)
        if (res.authSetting[`scope.${auth}`]) {
        onSuccess(res)
        } else {
        onFail(res)
        }
    },
    fail(err) {
        console.log(err)
    }
    })
}

export function getUserInfo(onSuccess, onFail) {
    mpvue.getUserInfo({
        success(res) {
            const { userInfo } = res
            console.log(userInfo)
            onSuccess(userInfo)
        },
        fail(res) {
            console.log(res)
        }
    })
}

export function setStorageSync(key, value) {
    mpvue.setStorageSync(key,value)
}

export function getStorageSync(key) {
    return mpvue.getStorageSync(key)
}

export function getOpenId (userInfo) {
    const { gender, avatarUrl, nickName, city} = userInfo
    console.log(gender)
    return new Promise((reslove, reject) => {
        mpvue.login({
            success(res) {
                const { code } = res
                getOpenLocation().then(result => {
                    console.log(res)
                    const { latitude, longitude, address } = result
                    if (code) {
                        reslove(code)
                        post(api.login, {
                            code,
                            gender: gender,
                            nickName,
                            avatar: avatarUrl,
                            longitude: longitude.toString(),
                            latitude: latitude.toString(),
                            address
                        }).then(res => {
                            console.log(res)
                            if (res.data.data.openId) {
                                setStorageSync('openId', res.data.data.openId)
                                setStorageSync('token', res.data.data.token)
                                setStorageSync('ruleId', 81)
                            }
                        })
                    }
                })
            },
            fail(err) {
                reject(err)
            }
        })
    })
}

export function getOpenLocation () {
    return new Promise((resolve, reject) => {
        wx.chooseLocation({
            success (res) {
                resolve(res)
            }
        })
    })
}
